namespace Stock.WinForm
{
    using System.Collections.Generic;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using Stock.Bl;
    using Stock.Model;

    public partial class OptInput : Form
    {
        public OptInput()
        {
            InitializeComponent();

            DataGridViewColumn dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.Width = 160;
            dgvc.DataPropertyName = "Opt_Date";
            dgvc.HeaderText = "操作日期";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;

            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.Width = 100;
            dgvc.DataPropertyName = "Opt_Code";
            dgvc.HeaderText = "股票代码";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgvc.Width = 150;
            dgvc.DataPropertyName = "S_Name";
            dgvc.HeaderText = "股票名称";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.Width = 120;
            dgvc.DataPropertyName = "Parameter_Name";
            dgvc.HeaderText = "操作类别";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvc.Width = 100;
            dgvc.DataPropertyName = "Opt_Copies";
            dgvc.HeaderText = "操作份额";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvc.Width = 100;
            dgvc.DataPropertyName = "Opt_Price";
            dgvc.HeaderText = "单价";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            dgvc.DefaultCellStyle.Font = new Font("华文新魏", 10.5F, FontStyle.Italic);
            dgvc.Width = 180;
            dgvc.DataPropertyName = "Opt_Sum";
            dgvc.HeaderText = "费用合计";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvc.DefaultCellStyle.Font = new Font("华文新魏", 10.5F, FontStyle.Bold);
            dgvc.DefaultCellStyle.ForeColor = Color.DarkGreen;
            dgvc.Width = 120;
            dgvc.DataPropertyName = "Opt_Sum";
            dgvc.HeaderText = "操作费用";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);

            dgvc = new DataGridViewTextBoxColumn();
            dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvc.DefaultCellStyle.Font = new Font("华文新魏", 10.5F, FontStyle.Bold);
            dgvc.DefaultCellStyle.ForeColor = Color.DarkGreen;
            dgvc.Width = 120;
            dgvc.DataPropertyName = "Opt_ID";
            dgvc.HeaderText = "Opt_ID";
            dgvc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvc.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
            dataGridView1.Columns.Add(dgvc);
            dataGridView1.Columns[8].Visible = false;

            dataGridView1.RowHeadersVisible = false;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = System.Drawing.Color.Lavender;//System.Drawing.Color.FromArgb(60, 250, 240, 230);
            dataGridView1.AllowUserToOrderColumns = false;

            foreach (DataGridViewColumn cdd in dataGridView1.Columns)
            {
                cdd.SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            dataGridView1.EnableHeadersVisualStyles = false;
            dataGridView1.Columns[0].HeaderCell.Style.ForeColor = Color.Yellow;
            dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.SteelBlue;
            dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = SystemColors.Info;
            dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("楷体_GB2312", 14F, FontStyle.Regular);
            dataGridView1.ColumnHeadersHeight = 60;
            //dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Gainsboro;
            dataGridView1.DefaultCellStyle.BackColor = Color.Gainsboro;

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.AllowUserToResizeColumns = false;
            dataGridView1.AllowUserToResizeRows = false;

            //dataGridView1.AlternatingRowsDefaultCellStyle.SelectionBackColor = System.Drawing.Color.Fuchsia;
        }

        /// <summary>
        /// 限制输入为整数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void input_Integer_Press(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            e.Handled = true;
            if (char.IsDigit(e.KeyChar) || e.KeyChar == (char)0x08)
            {
                e.Handled = false;
            }
            if (e.KeyChar == 45)                       //负数
            {
                string txtValue = ((System.Windows.Forms.TextBox)sender).Text;

                if (txtValue.Length > 0)
                    e.Handled = true;           //只能是第一位
                else
                {
                    e.Handled = false;
                }
            }
        }

        /// <summary>
        /// 限制输入为浮点数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void input_float_Press(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
            {
                e.Handled = true;
            }

            if (e.KeyChar == 46)                       //小数点
            {
                string txtValue = ((System.Windows.Forms.TextBox)sender).Text;

                if (txtValue.Length <= 0)
                    e.Handled = true;           //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(txtValue, out oldf);
                    b2 = float.TryParse(txtValue + e.KeyChar.ToString(), out f);
                    if (b2 == true)
                    {
                        if (b1 == false)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }
            }

            if (e.KeyChar == 45)                       //负数
            {
                string txtValue = ((System.Windows.Forms.TextBox)sender).Text;

                if (txtValue.Length > 0)
                    e.Handled = true;           //只能是第一位
                else
                {
                    e.Handled = false;
                }
            }
        }

        /// <summary>
        ///  初期装载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OptInput_Load(object sender, System.EventArgs e)
        {
            //OptInputBll optInputBll = new OptInputBll();
            //DateTime asd = optInputBll.getMinOptDate();
            // optInputBll.getInMoneyBeforDate(asd.AddDays(-1), DateTime.Now);
            //optInputBll.getRemainingMoneyBeforDate(DateTime.Now);
            //optInputBll.bactchCalcGain();
            //optInputBll.getFridayList(asd.AddDays(-1), DateTime.Now);
            //optInputBll.getInMoneyBeforDate(DateTime.Now);
            //new Stock.Bl.StockInfoBl().UpdateAllInfo();
            this.cmbType.SelectedIndex = 0;
            this.RefreshGridView();
        }

        private void RefreshGridView()
        {
            try
            {
                dataGridView1.Rows.Clear();
                OptInputBll optInputBll = new OptInputBll();
                List<StockOptHisEntity> lstData = optInputBll.getStockDataList();
                decimal decFee;
                decimal feeSum = 0m; ;
                foreach (StockOptHisEntity sohe in lstData)
                {
                    if (sohe.Type == "证券买入" || sohe.Type == "证券卖出")
                    {
                        if (sohe.Type == "证券买入")
                        {
                            decFee = System.Math.Abs(sohe.Amount) - (int)sohe.Copies * (decimal)sohe.Price;
                        }
                        else
                        {
                            decFee = (int)sohe.Copies * (decimal)sohe.Price - System.Math.Abs(sohe.Amount);
                        }

                        feeSum += decFee;

                        dataGridView1.Rows.Add(new string[] { sohe.OptDate, sohe.StockID, sohe.StockName,
                    sohe.Type, formateInt(sohe.Copies), formateDecimal(sohe.Price),
                    sohe.Amount.ToString("#,##0.00"),decFee.ToString("#,##0.00") ,sohe.ID.ToString()});
                    }
                    else
                    {
                        dataGridView1.Rows.Add(new string[] { sohe.OptDate, sohe.StockID, sohe.StockName,
                    sohe.Type, formateInt(sohe.Copies), formateDecimal(sohe.Price),
                    sohe.Amount.ToString("#,##0.00"),"" ,sohe.ID.ToString()});
                    }
                }

                dataGridView1.Rows.Add(new string[] { "", "", "",
                    "", "", "",
                    "费用合计",feeSum.ToString("#,###.00"),"" });

                dataGridView1.Rows[dataGridView1.RowCount - 1].DefaultCellStyle.BackColor = Color.LightCoral;
            }
            catch { }
        }

        private string formateDecimal(decimal? decValue)
        {
            if (decValue == null)
            {
                return "";
            }
            else
            {
                return ((decimal)decValue).ToString("#,##0.000");
            }
        }

        private string formateInt(int? decValue)
        {
            if (decValue == null)
            {
                return "";
            }
            else
            {
                return ((int)decValue).ToString("#,###");
            }
        }

        /// <summary>
        /// 设定生成的Combobox
        /// </summary>
        /// <param name="comboBox">Combobox对象</param>
        /// <param name="p">有无空白行</param>
        private void setComboBox(ComboBox comboBox, bool p)
        {
            StockOptDetailBl stockOptDetailBl = new StockOptDetailBl();
            DataSet dsList = stockOptDetailBl.GetTypeDataList("Parameter_Type='1'");
            DataTable dt = dsList.Tables[0];
            if (p)
            {
                System.Data.DataRow drNon = dt.NewRow();
                drNon["Parameter_Value"] = "";
                drNon["Parameter_Name"] = "";
                dt.Rows.InsertAt(drNon, 0);
            }

            if (dt != null)
            {
                comboBox.DataSource = dt;//绑定数据.
                comboBox.DisplayMember = "Parameter_Name";//显示项
                comboBox.ValueMember = "Parameter_Value";//值项
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, System.EventArgs e)
        {
        }

        /// <summary>
        /// 清理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, System.EventArgs e)
        {
            this.txtCd.Text = "";
            this.textBox3.Text = "";
            this.txtCopies.Text = "";
            this.txtPrice.Text = "";
            this.txtAmount.Text = "";
            this.txtOptID.Text = "";
            this.dateTimePicker1.Value = System.DateTime.Now;
            this.cmbType.SelectedIndex = 0;
        }

        private decimal setEntityValue(TextBox tx)
        {
            decimal toValue = 0;
            if (tx.Text.Trim().Length > 0)
            {
                toValue = decimal.Parse(tx.Text.Trim());
            }
            return toValue;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            OptInputBll optInputBll = new OptInputBll();

            try
            {
                StockOptHisEntity stockOptHisEntity = new StockOptHisEntity();

                if (cmbType.SelectedItem.ToString() == "证券买入" || cmbType.SelectedItem.ToString() == "银行转出")
                {
                    stockOptHisEntity.Amount = 0 - System.Math.Abs(decimal.Parse(txtAmount.Text));
                }
                else
                {
                    stockOptHisEntity.Amount = System.Math.Abs(decimal.Parse(txtAmount.Text));
                }

                if (txtCopies.Text.Trim().Length > 0)
                {
                    stockOptHisEntity.Copies = (int)decimal.Parse(this.txtCopies.Text);
                }
                if (txtCopies.Text.Trim().Length > 0)
                {
                    stockOptHisEntity.Price = decimal.Parse(txtPrice.Text);
                }
                stockOptHisEntity.Remark = string.Empty;
                stockOptHisEntity.StockID = txtCd.Text;
                stockOptHisEntity.Type = cmbType.SelectedItem.ToString();
                stockOptHisEntity.UserID = 9999;
                stockOptHisEntity.OptDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");

                if (this.txtOptID.Text.Trim() == string.Empty)
                {
                    optInputBll.saveStockHisData(stockOptHisEntity);
                }
                else
                {
                    stockOptHisEntity.ID = int.Parse(this.txtOptID.Text);
                    optInputBll.saveEditStockHisData(stockOptHisEntity);
                }
            }
            catch
            {
                MessageBox.Show("Error");
            }

            RefreshGridView();
        }

        /// <summary>
        /// 双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //this.txtCd.ReadOnly = true;
            //this.txtCopies.ReadOnly = true;
            //this.txtPrice.ReadOnly = true;
            ////this.textBox4.ReadOnly = true;
            //this.txtOptID.ReadOnly = true;
            //this.dateTimePicker1.Enabled = false;
            //this.cmbType.Enabled = false;

            //this.txtCd.BackColor = System.Drawing.Color.LightGray;
            //this.txtCopies.BackColor = System.Drawing.Color.LightGray;
            //this.txtPrice.BackColor = System.Drawing.Color.LightGray;
            //// this.textBox4.BackColor = System.Drawing.Color.LightGray;
            //this.dateTimePicker1.BackColor = System.Drawing.Color.LightGray;
            //this.cmbType.BackColor = System.Drawing.Color.LightGray;
        }

        private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
        {
        }

        private void textBox6_Leave(object sender, System.EventArgs e)
        {
            StockOptDetailBl StockOptDetailBl = new StockOptDetailBl();

            StockInfoEntity ste = StockOptDetailBl.GetStockByKey(txtStock.Text);
            if (ste == null)
            {
                this.txtCd.Text = string.Empty;
                this.textBox3.Text = string.Empty;
                return;
            }
            this.txtCd.Text = ste.S_Code;
            this.textBox3.Text = ste.S_Name;
            this.txtStock.Text = ste.S_PYM;
        }

        private void dataGridView1_DoubleClick(object sender, System.EventArgs e)
        {
            if (dataGridView1.SelectedRows[0].Cells[8].Value != null && dataGridView1.SelectedRows[0].Cells[8].Value.ToString() != string.Empty)
            {
                if (dataGridView1.SelectedRows[0].Cells[1].Value != null)
                {
                    this.txtCd.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();

                    StockOptDetailBl StockOptDetailBl = new StockOptDetailBl();

                    StockInfoEntity ste = StockOptDetailBl.GetStockByKey(this.txtCd.Text);
                    if (ste == null)
                    {
                        this.txtCd.Text = string.Empty;
                        this.textBox3.Text = string.Empty;
                        return;
                    }
                    this.txtCd.Text = ste.S_Code;
                    this.textBox3.Text = ste.S_Name;
                    this.txtStock.Text = ste.S_PYM;
                }
                if (dataGridView1.SelectedRows[0].Cells[4].Value != null)
                {
                    this.txtCopies.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
                }
                if (dataGridView1.SelectedRows[0].Cells[5].Value != null)
                {
                    this.txtPrice.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
                }
                this.txtAmount.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();

                this.txtOptID.Text = dataGridView1.SelectedRows[0].Cells[8].Value.ToString();

                this.dateTimePicker1.Value = System.DateTime.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
                this.cmbType.SelectedValue = dataGridView1.SelectedRows[0].Cells[3].Value;
            }
        }

        private void btnQuery_Click_1(object sender, System.EventArgs e)
        {
            this.RefreshGridView();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }
        }

        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            return;
        }
    }
}